package com.rongshu.sendmessage.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.rongshu.sendmessage.R;
import com.rongshu.sendmessage.activity.DingWeiActivity;
import com.rongshu.sendmessage.activity.seeImages.PictureDisplayActivity;
import com.rongshu.sendmessage.activity.seeImages.PictureDisplayActivityTwo;
import com.rongshu.sendmessage.adapter.CatogryOneAdapter;
import com.rongshu.sendmessage.adapter.CatogryThreeAdapter;
import com.rongshu.sendmessage.adapter.CatogryTwoAdapter;
import com.rongshu.sendmessage.adapter.PayAdapter;
import com.rongshu.sendmessage.base.BaseActivity;
import com.rongshu.sendmessage.base.BaseFragment;
import com.rongshu.sendmessage.base.MyApplication;
import com.rongshu.sendmessage.bean.CatogryInfoBean;
import com.rongshu.sendmessage.bean.FileBean;
import com.rongshu.sendmessage.bean.PaySelectBean;
import com.rongshu.sendmessage.bean.WXPayBean;
import com.rongshu.sendmessage.fragment.util.AddImageAdapter;
import com.rongshu.sendmessage.util.ClientPublicParamUtil;
import com.rongshu.sendmessage.util.DialogUtil;
import com.rongshu.sendmessage.util.ObjectUtil;
import com.rongshu.sendmessage.util.ObjectUtils;
import com.rongshu.sendmessage.util.PhotoImageLoader;
import com.rongshu.sendmessage.util.StringUtils;
import com.rongshu.sendmessage.util.ToastUtils;
import com.rongshu.sendmessage.util.Utils;
import com.rongshu.sendmessage.util.addimage.ActivityResultCallback;
import com.rongshu.sendmessage.util.addimage.DialogUitl;
import com.rongshu.sendmessage.util.addimage.ImageResultCallback;
import com.rongshu.sendmessage.util.addimage.ProcessImageUtil;
import com.rongshu.sendmessage.util.addimage.UpFileUtil;
import com.rongshu.sendmessage.util.httpUtil.HYContent;
import com.rongshu.sendmessage.util.httpUtil.IModel;
import com.rongshu.sendmessage.util.itemDecoration.MyItemDecoration;
import com.rongshu.sendmessage.util.itemDecoration.MyItemDecoration2;
import com.rongshu.sendmessage.util.itemDecoration.MyItemDecoration3;
import com.rongshu.sendmessage.util.wxPayUtil.PayListenerUtils;
import com.rongshu.sendmessage.util.wxPayUtil.PayResultListener;
import com.rongshu.sendmessage.util.wxPayUtil.PayUtils;
import com.rongshu.sendmessage.view.TitileLayout;
import com.rongshu.sendmessage.view.bottomView.CatogryBottomDialog;

import org.json.JSONException;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import static com.lzy.imagepicker.ui.ImageGridActivity.EXTRAS_IMAGES;
import static com.rongshu.sendmessage.util.DialogUtil.hideProgress;
import static com.rongshu.sendmessage.util.DialogUtil.showProgress;
import static com.rongshu.sendmessage.util.httpUtil.HYContent.REQUSET_CODE;

public class SendFragment extends BaseFragment implements View.OnClickListener, PayResultListener {
    private final int REQUEST_CODE = 111;
    private TitileLayout tv_title;
    private TextView tv_weizhi;
    private TextView tv_fabu, tv_fabu_number, tv_dingzhi, tv_dingzhi_number;
    private ImageView iv_select_fabu, iv_select_dingzhi;
    private View re_dingzhi, re_fabu,re_wx_pay;
    private Context mContext;
    private Intent mIntent;
    private String latlugStr;
    private String userId;
    private String address;
    private EditText et_title;
    private EditText et_detail;
    private RecyclerView mRecyclerImageView;
//    上传时的文件路径
    private List<FileBean> backImageList = new ArrayList<>();
    private List<PaySelectBean> paySelectList = new ArrayList<>();
    private TextView tv_catgroy;
    private View ll_listViews;
    private NestedScrollView nestedScrollView;
    private TextView tv_number;
    private RecyclerView payRecycleView;
    private PayAdapter mPayAdapter;
    private int paySelectIndex=-1;
    private int upPosition;
    private CatogryInfoBean locationBean;
    private boolean toppingIsNo=false;
    private String userHead;
    private EditText et_phone;
    private String orderId;
    private String payId;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getContext();
        userId = MyApplication.mSettings.getString(HYContent.UserId, "");
        userHead=MyApplication.mSettings.getString(HYContent.AvatarUrl, "");
        initPhotoPicker();
        PayListenerUtils.getInstance(mContext).addListener(this);
        initPaySelectData();
    }

    private void initPaySelectData() {
        Map<String, String> param = new HashMap<>();
        DialogUtil.showProgress(mContext);
        paySelectList.clear();
        param.put("clientPublicParam", ClientPublicParamUtil.getPublicParams(mContext));
        String url = new HYContent().PAY_SELECT_LIST_URL;
        OkGo.<String>post(url).params(param).tag("PAY_SELECT_LIST_URL").execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                IModel.AjaxResult jr = new IModel.AjaxResult(response.body());
                final int code = jr.getCode();
                if (code > 0) {
                    List<PaySelectBean> beans = JSON.parseArray(jr.getJSONArrayData().toString(), PaySelectBean.class);
                    paySelectList.addAll(beans);
                    mPayAdapter.notifyDataSetChanged();
                }

                DialogUtil.hideProgress();
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                DialogUtil.hideProgress();
            }
        });
    }
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.activity_send_message, null);
        initView(rootView);
        return rootView;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        PayListenerUtils.getInstance(getContext()).removeListener(this);
    }

    private void initView(View rootView) {
        View btn_dingwei = rootView.findViewById(R.id.btn_dingwei);
        View titleLayLeft = rootView.findViewById(R.id.titleLayLeft);
        tv_number = rootView.findViewById(R.id.tv_number);
        et_phone = rootView.findViewById(R.id.et_phone);
        et_phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s == null || StringUtils.isEmpty(s.toString())) {

                } else {
                    String s1 = s.toString();
                    if (s1.length() > 15) {
                        s1 = s1.substring(0, 15);
                        et_detail.setText(s1);
                        et_detail.setSelection(s1.length());
                        ToastUtils.show(mContext,"电话位数不能超过15位");
                    }
                }
            }
        });
        titleLayLeft.setVisibility(View.GONE);
        View btn_catogry = rootView.findViewById(R.id.btn_catogry);
        nestedScrollView = rootView.findViewById(R.id.nestedScrollView);
        tv_catgroy = rootView.findViewById(R.id.tv_catgroy);
        ll_listViews = rootView.findViewById(R.id.ll_listViews);
//        ll_listViews.setAnimation(AnimationUtil.getApleAnimation());
        btn_catogry.setOnClickListener(view -> {
//            if (ll_listViews.getVisibility() == View.VISIBLE) {
//                ll_listViews.setVisibility(View.GONE);
//            } else {
//                ll_listViews.setVisibility(View.VISIBLE);
//
//            }
            //弹框选择类别
            CatogryBottomDialog dialog=new CatogryBottomDialog(mContext,locationBean, new DialogUtil.OnDialogEvent<CatogryInfoBean>(){
                @Override
                public void onPositiveButtonClick(CatogryInfoBean s) {
                    super.onPositiveButtonClick(s);
                    locationBean=s;
                    tv_catgroy.setText(locationBean.getName());
                }
            });
            dialog.showDialog();
        });
        TextView title = rootView.findViewById(R.id.title);
        title.setText("信息发布");
        mRecyclerImageView = rootView.findViewById(R.id.recycleView);
        initImageRecycleView();
        payRecycleView = rootView.findViewById(R.id.payRecycleView);
        initPayRecycleView();
        tv_weizhi = rootView.findViewById(R.id.tv_weizhi);
        re_dingzhi = rootView.findViewById(R.id.re_dingzhi);
        re_wx_pay = rootView.findViewById(R.id.re_wx_pay);
        re_fabu = rootView.findViewById(R.id.re_fabu);
        View btn_submit = rootView.findViewById(R.id.btn_submit);
        btn_dingwei.setOnClickListener(this);
        re_fabu.setOnClickListener(this);
        re_dingzhi.setOnClickListener(this);
        btn_submit.setOnClickListener(this);
        tv_fabu = rootView.findViewById(R.id.tv_fabu);
        iv_select_fabu = rootView.findViewById(R.id.iv_select_fabu);
        tv_fabu_number = rootView.findViewById(R.id.tv_fabu_number);
        tv_dingzhi = rootView.findViewById(R.id.tv_dingzhi);
        iv_select_dingzhi = rootView.findViewById(R.id.iv_select_dingzhi);
        tv_dingzhi_number = rootView.findViewById(R.id.tv_dingzhi_number);
//        et_title=rootView.findViewById(R.id.et_title);
        et_detail = rootView.findViewById(R.id.et_detail);
        et_detail.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s == null || StringUtils.isEmpty(s.toString())) {

                    tv_number.setText("0/300");
                } else {
                    String s1 = s.toString();
                    if (s1.length() > 300) {
                        s1 = s1.substring(0, 300);
                        et_detail.setText(s1);
                        et_detail.setSelection(s1.length());
                        ToastUtils.show(mContext,"文字最多允许输入300字符噢");
                    }
                    tv_number.setText(s1.length() + "/300");
                }

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_dingwei://定位
//                et_weizhi.setText(MyApplication.mSettings.getString(HYContent.CITY,""));

                mIntent = new Intent(mContext, DingWeiActivity.class);
                startActivityForResult(mIntent, REQUSET_CODE);
                break;
            case R.id.re_fabu://普通发布方式
                setSelectType("fabu");
                toppingIsNo=false;
                re_wx_pay.setVisibility(View.GONE);
                payRecycleView.setVisibility(View.GONE);
                break;
            case R.id.re_dingzhi://顶置方式
                setSelectType("dingzhi");
                toppingIsNo=true;
                re_wx_pay.setVisibility(View.VISIBLE);
                payRecycleView.setVisibility(View.VISIBLE);
                break;
            case R.id.btn_submit://提交
                if (et_detail.getText().length() <= 0) {
                    ToastUtils.show(mContext, "请输入内容");
                    return;
                }
                if (locationBean==null) {
                    ToastUtils.show(mContext, "请选择类目");
                    return;
                }
                if (re_wx_pay.getVisibility()==View.VISIBLE){
                    //支付
                    getPayData();
                }else{
                    submit();
                }

                break;

        }
    }

    private void getPayData() {
        if (paySelectIndex==-1){
            ToastUtils.show(mContext,"请先选择支付金额");
            return;
        }
        Map<String, String> param = new HashMap<String, String>();
        param.put("userId", userId);
        param.put("total_yuan", paySelectList.get(paySelectIndex).getPriceMoneyYuan());//支付10元10
        param.put("chargingStandardConfigurationId", paySelectList.get(paySelectIndex).getId());//支付10元10
        param.put("clientPublicParam", ClientPublicParamUtil.getPublicParams(mContext));
        String url = new HYContent().WX_PAY_URL;
        DialogUtil.showProgress(mContext);
        ObjectUtils.hideKeyboard(et_detail);
        OkGo.<String>post(url).params(param).tag("SEND_MESSAGE_URL").execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                IModel.AjaxResult jr = new IModel.AjaxResult(response.body());
                final int code = jr.getCode();
                if (code > 0) {
                    WXPayBean wxPayBean=JSON.parseObject(jr.getData().toString(), WXPayBean.class);
                    HashMap<String ,String >map=new HashMap<>();
                    map.put("sign",wxPayBean.getSign());
                    map.put("nonce_str",wxPayBean.getNoncestr());
                    map.put("prepay_id",wxPayBean.getPrepayid());
                    map.put("app_id",wxPayBean.getAppid());
                    map.put("partner_id",wxPayBean.getPartnerid());
                    map.put("timestamp",wxPayBean.getTimestamp());
                    map.put("package",jr.getData().getString("package"));
                    PayUtils instance = PayUtils.getInstance(mContext);
                    instance.pay(PayUtils.PAY_TYPE_WX, map);
                    payId=wxPayBean.getPayId();
                    orderId=wxPayBean.getOrderId();
                } else {
                    ToastUtils.show(mContext, jr.getMsg());
                }
                DialogUtil.hideProgress();
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                DialogUtil.hideProgress();
            }
        });
    }

    private void submit() {
        Map<String, String> param = new HashMap<String, String>();
        String cityCode = MyApplication.mSettings.getString(HYContent.CITY_CODE, "");
        param.put("regionId", cityCode);
        param.put("regionId", cityCode);
        param.put("regionId", cityCode);
        param.put("articleCategoryId", locationBean.getTypeid() + "");
        param.put("articleCategoryName", locationBean.getName());
        String gender = MyApplication.mSettings.getString(HYContent.Gender, "");
        param.put("releaseUserSex", gender);
        param.put("contactPhone", et_phone.getText().toString());//字段名称不一定
        param.put("releaseUserHeadPortrait", userHead);
        if (!StringUtils.isEmpty(latlugStr) && latlugStr.split(",").length == 2) {
            param.put("longitudeStr", latlugStr.split(",")[0]);
            param.put("latitudeStr", latlugStr.split(",")[1]);
            org.json.JSONObject jo = new org.json.JSONObject();
            try {
                jo.put("wxUserPosition", address);
                jo.put("longitude", latlugStr.split(",")[0]);
                jo.put("latitude", latlugStr.split(",")[1]);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            param.put("mapLocationJsonStr", jo.toString());
        } else {
            param.put("longitudeStr", "");
            param.put("latitudeStr", "");
            param.put("mapLocationJsonStr", "");
        }
        param.put("address", address);//地址
        if (paySelectIndex>=0){
            param.put("chargingStandardConfigurationId", paySelectList.get(paySelectIndex).getId());//支付id
            param.put("orderId", orderId);//支付 订单号
        }
        param.put("releaseUsernick", MyApplication.mSettings.getString(HYContent.NickName, ""));//发布人的名称
        param.put("releaseUserId", userId);//发布人的头像
        StringBuilder images = new StringBuilder();
        for (int i = 0; i < backImageList.size(); i++) {
            images.append(backImageList.get(i).getUploadFileId());
            if (i != backImageList.size() - 1) {
                images.append(",");
            }
        }
        param.put("imgUrlIds", images.toString());//图片id字符串，英文逗号隔开两个id之间：
        param.put("toppingIsNo", toppingIsNo+"");//是否置顶
        param.put("content", et_detail.getText().toString());//发布内容
        param.put("clientPublicParam", ClientPublicParamUtil.getPublicParams(mContext));
        String url = new HYContent().SEND_MESSAGE_URL;
        DialogUtil.showProgress(mContext);
        ObjectUtils.hideKeyboard(et_detail);
        OkGo.<String>post(url).params(param).tag("SEND_MESSAGE_URL").execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                IModel.AjaxResult jr = new IModel.AjaxResult(response.body());
                final int code = jr.getCode();
                if (code > 0) {
                    ToastUtils.show(mContext, "信息发布成功");
                    latlugStr = "";
                    locationBean=null;
                    address = "";
                    et_detail.setText("");
                    et_phone.setText("");
                    backImageList.clear();
                    mImageList.clear();
                    mImageList.add(R.mipmap.new_add_photo + "");
                    mImageAdapter.notifyDataSetChanged();
                    tv_catgroy.setText("");
                    tv_weizhi.setText("");
                } else {
                    ToastUtils.show(mContext, jr.getMsg());
                }
                DialogUtil.hideProgress();
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                DialogUtil.hideProgress();
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==1001){
            if (data != null) {
                int index = data.getIntExtra("index", 0);
                mImageList.remove(index);
                backImageList.remove(index);
                if (mImageList.size()>0&&mImageList.size()<=6){
                    if (!mImageList.get(mImageList.size()-1).equals(R.mipmap.new_add_photo+"")){
                        mImageList.add(R.mipmap.new_add_photo+"");
                    }
                }else{
                    mImageList.add(R.mipmap.new_add_photo+"");
                }

                mImageAdapter.setList(mImageList);
                mImageAdapter.notifyDataSetChanged();

            }
        }
        if (requestCode == REQUSET_CODE && resultCode == 90) {
            if (data != null && data.hasExtra("address")) {
                address = data.getStringExtra("address");
                latlugStr = data.getStringExtra("latlugStr");
                tv_weizhi.setText(address);
            }
        }
        if (requestCode==REQUEST_CODE&&resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == REQUEST_CODE) {
                images.clear();
                ArrayList<ImageItem> images1=(ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                images.addAll(images1);
                if (images!=null&&images.size()>0){
                    upPosition=0;
                    showProgress(mContext);
                    goUpImage(upPosition);
                }
            } else {
                Toast.makeText(mContext, "没有数据", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void goUpImage(int position) {
        if (images.size()-1<position){
            hideProgress();
            images.clear();
            return;
        }
        String path=images.get(position).path;
        File file=new File(path);
        Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
        Uri uri = FileProvider.getUriForFile(mContext, getActivity().getPackageName()
                + ".fileImageProvider", file);
        upLoadImg(bitmap,uri+"",file);
    }

    private void setSelectType(String type) {
        if (type.equals("dingzhi")) {
            tv_dingzhi.setTextColor(getResources().getColor(R.color.blue_2b));
            tv_dingzhi_number.setTextColor(getResources().getColor(R.color.blue_2b));
            iv_select_dingzhi.setVisibility(View.VISIBLE);
            tv_fabu.setTextColor(getResources().getColor(R.color.blak_333));
            tv_fabu_number.setTextColor(getResources().getColor(R.color.blak_333));
            iv_select_fabu.setVisibility(View.GONE);
            re_dingzhi.setBackgroundResource(R.drawable.blue_e7_2conver_shape);
            re_fabu.setBackgroundResource(R.drawable.gray_f8_2conver_shape);
        } else {
            tv_fabu.setTextColor(getResources().getColor(R.color.blue_2b));
            tv_fabu_number.setTextColor(getResources().getColor(R.color.blue_2b));
            iv_select_fabu.setVisibility(View.VISIBLE);
            tv_dingzhi.setTextColor(getResources().getColor(R.color.blak_333));
            tv_dingzhi_number.setTextColor(getResources().getColor(R.color.blak_333));
            iv_select_dingzhi.setVisibility(View.GONE);
            re_fabu.setBackgroundResource(R.drawable.blue_e7_2conver_shape);
            re_dingzhi.setBackgroundResource(R.drawable.gray_f8_2conver_shape);
        }
    }
    //    添加图片的流程

    private AddImageAdapter mImageAdapter;
    private ArrayList<String> mImageList;

    private void initImageRecycleView() {
        GridLayoutManager manager = new GridLayoutManager(mContext, 3);
        manager.setOrientation(GridLayoutManager.VERTICAL);
        mRecyclerImageView.setLayoutManager(manager);
        //把自定义的ItemDecoration设置给RecyclerView
        mRecyclerImageView.addItemDecoration(new MyItemDecoration2());
        //设置设置RecyclerView的适配器Adapter
        mImageList = new ArrayList<>();
        mImageAdapter = new AddImageAdapter(mImageList, new AddImageAdapter.OnRecycleViewItemClickListener() {
            @Override
            public void OnItemClick(View view, int position) {
                if (view.getId()==R.id.iv_delete){
                    mImageList.remove(position);
                    backImageList.remove(position);
                    if (mImageList.size()>0&&mImageList.size()<=6){
                        if (!mImageList.get(mImageList.size()-1).equals(R.mipmap.new_add_photo+"")){
                            mImageList.add(R.mipmap.new_add_photo+"");
                        }
                    }else{
                        mImageList.add(R.mipmap.new_add_photo+"");
                    }
                    mImageAdapter.setList(mImageList);
                    mImageAdapter.notifyDataSetChanged();
                }else {
                    if (position == mImageList.size() - 1) {
                        if (mImageList.size() == 6) {
                            if (!(R.mipmap.new_add_photo + "").equals(mImageList.get(5))) {
                                seeImages(position);
                                return;
                            }
                        }
                        images.clear();
                        upImageBack();
                    } else {
                        seeImages(position);
                    }
                }
            }
        });
        mRecyclerImageView.setAdapter(mImageAdapter);

        initImageData();
    }

    private void seeImages(int position) {
        //查看图片，
        String path = mImageList.get(position);
        Uri uri = Uri.fromFile(new File(path));
        Intent intent = new Intent(mContext, PictureDisplayActivityTwo.class);
        intent.putExtra("img_url", uri + "");
        intent.putExtra("index", position);
        intent.putExtra("isCanDelete", true);
        try {
            ArrayList<String> listUri = new ArrayList<>();
            for (int i = 0; i < mImageList.size(); i++) {
                if ((R.mipmap.new_add_photo + "").equals(mImageList.get(i))) {
                    continue;
                }
                listUri.add(mImageList.get(i));
            }
            intent.putStringArrayListExtra("uris", listUri);
            startActivityForResult(intent,1001);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initPayRecycleView() {
        GridLayoutManager manager = new GridLayoutManager(mContext, 2);
        manager.setOrientation(GridLayoutManager.VERTICAL);
        payRecycleView.setLayoutManager(manager);
        //把自定义的ItemDecoration设置给RecyclerView
        payRecycleView.addItemDecoration(new MyItemDecoration(10,10));
        //设置设置RecyclerView的适配器Adapter
        paySelectList = new ArrayList<>();
        mPayAdapter = new PayAdapter(mContext,paySelectList);
        payRecycleView.setAdapter(mPayAdapter);
        mPayAdapter.setOnItemClickListener(position -> {
            paySelectIndex=position;
            for (int i = 0; i < paySelectList.size(); i++) {
                if (position==i){
                    paySelectList.get(i).setSelect(true);
                }else{
                    paySelectList.get(i).setSelect(false);
                }
            }
            mPayAdapter.notifyDataSetChanged();

        });
    }



    /**
     * 判断是否有某项权限
     *
     * @param string_permission 权限
     * @param request_code      请求码
     * @return
     */
    public boolean checkReadPermission(String string_permission, int request_code) {
        boolean flag = false;
        if (ContextCompat.checkSelfPermission(mContext, string_permission) == PackageManager.PERMISSION_GRANTED) {//已有权限
            flag = true;
        } else {//申请权限
            ActivityCompat.requestPermissions(getActivity(), new String[]{string_permission,
                            Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    request_code);
        }
        return flag;
    }

    /**
     * 检查权限后的回调
     *
     * @param requestCode  请求码
     * @param permissions  权限
     * @param grantResults 结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 10:
                for (int grantResult : grantResults) {
                    if (grantResult == PackageManager.PERMISSION_DENIED) {
                        Toast.makeText(getActivity(), "请允许权限后再试", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                upImageBack();
                break;
        }
    }
    private void initImageData() {
        mImageList.clear();
        backImageList.clear();
        mImageList.add(R.mipmap.new_add_photo + "");


    }


    @SuppressLint("HandlerLeak")
    private void upLoadImg(Bitmap bitmap, final String uri, File file) {
        //上传图片
        UpFileUtil.upFile(new HYContent().ADD_HEAD_FILE_URL, bitmap, file, new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                if (msg.what == UpFileUtil.SAVE_SUCCESS) {
                    String body = msg.obj + "";
                    Log.e("upFile", "上传成功" + body);
                    IModel.AjaxResult jr = new IModel.AjaxResult(body);
                    JSONObject jo = jr.getJsonObj();
                    FileBean fileBean = new FileBean();
                    fileBean.setDelete(true);
                    fileBean.setFielName(uri);
                    fileBean.setFileUrl(jo.getString("fileUrl"));
                    fileBean.setFileSize(jo.getString("fileSize"));
                    fileBean.setUploadFileId(jo.getString("uploadFileId"));
                    fileBean.setName(jo.getString("name"));
                    backImageList.add(fileBean);
                    if (mImageList.size()>=1){
                        mImageList.add(mImageList.size()-1,uri + "");
                    }else{
                        mImageList.add(uri + "");
                    }

                    if (mImageList.size() > 6) {
                        mImageList.remove(mImageList.size() - 1);
                    }
                    mImageAdapter.setList(mImageList);
                    mImageAdapter.notifyDataSetChanged();
                    upPosition++;
                    goUpImage(upPosition);
                    //上传文件
                }
            }
        });
    }


    @Override
    public void onPaySuccess() {
        Log.e("onPayFinish " , "支付成功");
        submit();
    }

    @Override
    public void onPayError() {
        ToastUtils.show(mContext,"支付失败");

    }

    @Override
    public void onPayCancel() {
        ToastUtils.show(mContext,"支付取消");

    }
    /**
     * 初始化图片选择器
     */
    private void initPhotoPicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new PhotoImageLoader());  //设置图片加载器
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setCrop(false);        //允许裁剪（单选才有效）
        imagePicker.setSelectLimit(6);
        imagePicker.setMultiMode(true);
    }
    public void upImageBack() {
        int result = ActivityCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (result == PackageManager.PERMISSION_DENIED) {//PERMISSION_GRANTED
            String[] permissions = {/*Manifest.permission.WRITE_EXTERNAL_STORAGE,*/
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE};
            ActivityCompat.requestPermissions((BaseActivity)mContext, permissions, 11);
        } else {
            startPhotoSelector();
        }
    }
    private ArrayList<ImageItem> images = new ArrayList<>();
    private void startPhotoSelector() {
        Intent intent = new Intent(mContext, ImageGridActivity.class);
        intent.putExtra(EXTRAS_IMAGES, images);
        startActivityForResult(intent, REQUEST_CODE);
    }
}
